package com.example.homework

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.example.homework.databinding.ActivityMainBinding
import com.example.homework.repositories.WordRepository
import com.example.homework.viewmodels.WordViewModel
import com.example.homework.viewmodels.WordViewModelFactory
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val wordViewModel: WordViewModel by viewModels<WordViewModel> {
        WordViewModelFactory(WordRepository((application as App).db.wordDao()))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        with(binding) {
            addButton.setOnClickListener {
                addWord(wordEditText.text.toString())
            }
            clearButton.setOnClickListener {
                clearAll()
            }
            lifecycleScope.launch {
                wordViewModel.firstFive.collect {
                    resultTextView.text = it.joinToString(separator = "\r\n")
                }
            }
        }
    }

    private fun addWord(word: String) {
        if (isValid(word))
            wordViewModel.addWord(word)
        else
            Snackbar.make(
                binding.addButton,
                "Only letters and dash is allowed!!!",
                Snackbar.LENGTH_LONG
            ).show()
    }

    private fun clearAll() {
        wordViewModel.cleanAll()
    }

    private fun isValid(word: String): Boolean =
        word.isNotEmpty() && word.matches(Regex("^[a-zA-Z-]+\$"))
}